<template>
  <div>
    <a-table
      :columns="columns"
      :data-source="optionData.conditions"
      row-key="condition_name"
      :pagination="false"
      bordered
      ref="conditionRef"
      :custom-row="customRow"
    >
      <template #bodyCell="{ column, record, index }">
        <template v-if="column.dataIndex == 'count'">
          <a-button type="link">{{ record.options.length }}</a-button>
        </template>

        <template v-if="column.dataIndex == 'action'">
          <!-- <MenuOutlined class="condition cursor-move text-primary" /> -->
          <a-button type="link" @click="condition_remove(index)">
            删除
          </a-button>
        </template>
      </template>
      <template #expandedRowRender="{ record }">
        <a-table
          :columns="optionsColumns"
          :data-source="record.options"
          :pagination="false"
          row-key="option_name"
          bordered
          :custom-row="option_move(record.condition_name, record.options)"
          @change="(_pagi, _filter, sorter) => handleChange(record, sorter)"
        >
          <template #bodyCell="{ column, record: optionRecord, index }">
            <template v-if="column.dataIndex == 'count'">
              <a-button type="link">
                {{ getMatchLen(optionRecord.matches) }}
              </a-button>
            </template>

            <template v-if="column.dataIndex == 'action'">
              <!-- <MenuOutlined class="" /> -->
              <a-button type="link" @click="remove(index, record.options)">
                删除
              </a-button>
            </template>
          </template>
        </a-table>
      </template>
    </a-table>
    <div text-center mt-4>
      <a-space>
        <a-button type="primary" @click="goPrev">上一步</a-button>
        <a-button type="primary" @click="finish">完成</a-button>
        <a-button @click="reset">重置</a-button>
      </a-space>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { Modal, TableColumnType } from 'ant-design-vue';
import { JobStep } from '../Step';
// import { MenuOutlined } from '@ant-design/icons-vue';
import type {
  FetchProcess,
  JumpType,
  Match,
  MatchData,
  OptionData,
  UpdateProcess,
} from '../type';
import useDrag from './useDrag';
import event from '../event';
import { syncCategory } from '@/api/hc_category';
import type { Category } from '@/types/category';

const props = defineProps<{
  stepData: JobStep;
  fetchProcess: FetchProcess;
  updateProcess: UpdateProcess;
}>();
const emits = defineEmits<{
  jump: [params: JumpType];
}>();

const { stepData, fetchProcess, updateProcess } = toRefs(props);

// 取第二部和第三步数据
const optionData = ref<OptionData>(
  cloneDeep(props.stepData.getStep('OPTION_RELATION')!.data) as OptionData,
);
const conditionData = ref<MatchData>(
  cloneDeep(props.stepData.getStep('CONDITION_RELATION')!.data) as MatchData,
);

const columns: TableColumnType[] = [
  {
    title: '条件',
    dataIndex: 'condition_name',
    customRender({ record }) {
      return record.alias_name || record.condition_name;
    },
  },
  {
    title: '匹配条件数',
    dataIndex: 'count',
  },
  {
    title: '操作',
    width: 250,
    dataIndex: 'action',
  },
];

const optionsColumns: TableColumnType[] = [
  {
    title: '选项',
    dataIndex: 'option_name',
    customRender({ record }) {
      return record.alias_name || record.condition_name;
    },
    sorter: true,
  },
  {
    title: '匹配选项数',
    dataIndex: 'count',
  },
  {
    title: '操作',
    width: 300,
    dataIndex: 'action',
  },
];

const swap = <T,>(arr: T[], i: number, j: number) => {
  // const temp = arr[j];
  // arr[j] = arr[i];
  // arr[i] = temp;
  const temp = arr[i];
  arr.splice(i, 1);
  arr.splice(j, 0, temp);
};

const remove = <T,>(index: number, list: T[]) => {
  list.splice(index, 1);
};
const reset = async () => {
  await fetchProcess.value('RESULT_ADJUST');
  optionData.value = cloneDeep(props.stepData.getStep('OPTION_RELATION')!.data);
  conditionData.value = cloneDeep(
    props.stepData.getStep('CONDITION_RELATION')!.data,
  );
};
const goPrev = () => {
  emits('jump', {
    process_name: 'OPTION_RELATION',
    callback: save,
  });
};

const save = async () => {
  stepData.value.updateStep('CONDITION_RELATION', conditionData.value);
  stepData.value.updateStep('OPTION_RELATION', optionData.value);
  const res = await updateProcess.value();
  if (res.code == 'ok') {
    stepData.value.isEdit = false;
    message.success('保存成功');
    return true;
  } else {
    // message.error(res.message);
    return false;
  }
};

const { categoryCode } = st.get('_category') as Category;

const finish = async () => {
  const res = await save();

  res &&
    Modal.confirm({
      content: '是否现在进行数据同步?',
      onOk: async () => {
        await syncCategory(categoryCode);
        event.emit('finish');
      },
      onCancel: () => {
        event.emit('finish');
      },
    });
};

// 条件移动位置需要更新第二步，第三步
const condition_move = (prev: number, next: number) => {
  swap(conditionData.value.conditions, prev, next);
  swap(optionData.value.conditions, prev, next);
};

const { customRow } = useDrag('condition', condition_move);

// 删除同理
const condition_remove = (idx: number) => {
  remove(idx, conditionData.value.conditions);
  remove(idx, optionData.value.conditions);
  stepData.value.isEdit = true;
};
const option_move = (name: string, data) => {
  return useDrag(name, (prev, next) => {
    swap(data, prev, next);
    stepData.value.isEdit = true;
  }).customRow;
};
const getMatchLen = (matches: Match[]) => {
  return matches.reduce((res, item) => {
    res += item.options.length;
    return res;
  }, 0);
};
// window._tb = optionData;
defineExpose({
  change: process_name => {
    emits('jump', {
      process_name,
      callback: save,
    });
  },
});

const conditionRef = ref();

const optionMap = ref(new Map());
const handleChange = (record, sorter) => {
  const { field, order } = sorter;
  if (field == 'option_name') {
    if (!optionMap.value.get(record.alias_name)) {
      optionMap.value.set(record.alias_name, cloneDeep(record.options));
    }
    switch (order) {
      case 'ascend':
        record.options.sort((a, b) => useSorter(a.alias_name, b.alias_name));
        break;
      case 'descend':
        record.options.sort((a, b) => useSorter(b.alias_name, a.alias_name));
        break;
      default:
        record.options = optionMap.value.get(record.alias_name);
    }
  }
};
</script>
